﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using StateGrid.GlobalVariables;

namespace StateGrid
{
    /// <summary>
    /// Summary description for UploadFile
    /// </summary>
    public class UploadFile
    {
        public UploadFile()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// 完成文件上传
        /// </summary>
        /// <param name="fileUpload">上传控件</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static Boolean Upload(FileUpload fileUpload,String fileName)
        {
            Boolean flag = true;

            //规范路径
            String filePath = FormatPath(GlobalResource.FILEPATH, fileName);
            if (null == filePath)
            {
                return false;
            }
            //检查文件路径是否存在，不存在则创建文件夹
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            //文件上传
            fileUpload.SaveAs(filePath + fileName);

            return flag;
        }



        /// <summary>
        /// 规范全文路径
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static String FormatPath(String filePath, String fileName)
        {
            if (null == fileName)
            {
                return fileName;
            }

            String[] str = fileName.Split(new Char[] { '-' });

            //只特殊处理索引编码
            Boolean f = true;
            //找出路径
            for (int i = 0; i < str.Length - 1; i++)
            {
                String s = str[i];

                if (f)
                {

                    //判断索引编码长度是不是偶数位
                    if (s.Length % 2 != 0)
                    {
                        return null;
                    }

                    for (int index = 0; index < s.Length; index++)
                    {
                        filePath += s[index++];
                        filePath += s[index];
                        filePath += '/';
                    }
                    f = false;
                }

                else
                {
                    filePath += s;
                    filePath += '/';
                }

            }

            return filePath;
        }
    }
}